package com.dankegongyu.lib.common.util;

import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;

/**
 * https://www.qimai.cn/app/rank/appid/685872176/country/cn
 *
 * @author wupuquan
 * @version 1.0
 * @since 2020/4/13 10:51
 */
public class ApkUtils {

    private static final String TAG = ApkUtils.class.getSimpleName();

    private ApkUtils() {
    }

    /**
     * 扫描本地安装的应用，不包含系统应用
     */
    @SuppressWarnings("UnusedReturnValue")
    @NonNull
    public static List<ApkInfo> scanLocalInstalledApps(PackageManager packageManager) {
        List<ApkInfo> apps = new ArrayList<>();
        try {
            List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
            for (int i = 0; i < packageInfos.size(); i++) {
                PackageInfo packageInfo = packageInfos.get(i);
                // 过滤掉系统app
                if ((ApplicationInfo.FLAG_SYSTEM & packageInfo.applicationInfo.flags) != 0) {
                    continue;
                }
                ApkInfo apk = new ApkInfo();
                apk.appName = packageInfo.applicationInfo.loadLabel(packageManager).toString();
                apk.packageName = packageInfo.packageName;
                apps.add(apk);
            }
        } catch (Throwable e) {
            Log.e(TAG, "===============获取应用包信息失败");
        }
        return apps;
    }

    @SuppressWarnings("WeakerAccess")
    public static class ApkInfo implements Serializable {
        private static final long serialVersionUID = -8001466928297783948L;

        public String appName;
        public String packageName;
    }
}
